package org.jkuang.qstar.commons.io;

import java.util.Arrays;

public class StopEnCoder {

	byte[] buffer;
	static final int ch8f = 0x8f;
	static final int chc0 = 0xc0;
	private int pos = 0;

	public StopEnCoder(int size) {
		this.buffer = new byte[size];
	}

	public void write(long vl) {
		ensureCapacity(pos + 8);
		long temp;
		if (vl < 0) {
			vl = -vl;
			temp = vl & 0x3f;
			buffer[pos++] = (byte) (0xc0 | temp);
		} else {
			temp = vl & 0x3f;
			buffer[pos++] = (byte) (0x80 | temp);
		}
		temp = vl >> 6;
		while (temp > 0) {
			buffer[pos++] = (byte) (temp & 0x7f);
			temp = temp >> 7;
		}
	}

	private void ensureCapacity(int minCapacity) {
		int oldCapacity = buffer.length;
		if (minCapacity > oldCapacity) {
			int newCapacity = Math.min(oldCapacity >>> 1 + 1, 256) + oldCapacity;
			if (newCapacity < minCapacity) {
				newCapacity = minCapacity;
			}
			buffer = Arrays.copyOf(buffer, newCapacity);
		}
	}

	public byte[] toByteArray() {
		byte[] bs = new byte[pos];
		System.arraycopy(buffer, 0, bs, 0, bs.length);
		return bs;
	}

}
